package com.ruoyi.edu.controller.front;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.edu.api.domain.EduComment;
import com.ruoyi.edu.service.IEduCommentService;
import com.ruoyi.user.api.domain.UcenterMember;
import com.ruoyi.user.api.feign.IUserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 前台评论模块
 *
 * @author isahino
 * @version 1.0
 * @date 2023/9/23 14:22
 */
@RestController
@RequestMapping("/front_comment")
public class FrontEduCommentController {

    @Autowired
    private IEduCommentService eduCommentService;
    @Resource
    private IUserClient iUserClient;

    /**
     * 根据课程id分页查询课程评论
     */
    @GetMapping("/page/{page}/{limit}/{courseId}")
    public AjaxResult getCommentPage(@PathVariable Integer page, @PathVariable Integer limit, @PathVariable String courseId) {
        Page<EduComment> commentPage = new Page<>(page, limit);
        LambdaQueryWrapper<EduComment> wrapper = new LambdaQueryWrapper<>();
        //判断课程id是否为空
        if (!StringUtils.isEmpty(courseId)) {
            wrapper.eq(EduComment::getCourseId, courseId);
        }
        //按发表时间新排序
        wrapper.orderByDesc(EduComment::getGmtCreate);
        //获得分页结果
        eduCommentService.page(commentPage, wrapper);
        return AjaxResult.success(commentPage);
    }

    /**
     * 添加评论
     */
    @PostMapping
    public AjaxResult addComment(HttpServletRequest request, @RequestBody EduComment eduComment) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //判断用户是否登录
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("您不处于登录状态，请登录后再发表评论");
        }
        eduComment.setMemberId(memberId);
        //远程调用 根据用户id获取用户信息
        AjaxResult memberInfo = iUserClient.getMemberInfo(memberId);
        if (!memberInfo.isSuccess()) {
            return AjaxResult.error("获取用户信息失败，请稍后重试");
        }
        UcenterMember member = JSON.parseObject(JSON.toJSONString(memberInfo.get(AjaxResult.DATA_TAG)), UcenterMember.class);
        eduComment.setAvatar(member.getAvatar());
        eduComment.setNickname(member.getNickname());
        //保存评论
        return eduCommentService.save(eduComment) ? AjaxResult.success("评论成功") : AjaxResult.error("发布评论失败，请稍后重试");
    }

}
